/**
 * Created by liujie on 2017/10/17.
 */
var dataTable;
var viewAddPage_url = "/editDeviceInfo";
var selectionArr = [];
var DeviceInfo = function ($) {

    var viewAccountList_url = "/deviceManage";
    var viewAddFastPage_url = "/editFastDeviceInfo";

    var viewAddDevice_url = "/editDeviceInfo/addBaseInfo";
    var viewAddCarDevice_url = "/editDeviceInfo/addCarInfo";
    var viewAddInstall_url = "/editDeviceInfo/addInstallInfo";
    function initTable() {
        dataTable = new BootstrapTable($('#tb_departments'),{
            url: '/deviceManage/queryDeviceList',
            sidePagination: "server",
            toolbar: '#toolbar',
            singleSelect:false,
            height:500,
            queryParams:function (params) {
               var _params = {
                   baseterminalid:$("#baseterminalid").val(),
                   baseTerminalSim:$("#baseTerminalSim").val(),
                   deptid:$("#deptid").val(),
                   basecarno:$("#basecarno").val(),
               };
                return $.extend(params,_params);
            },
            columns: [{
                checkbox: true
            }, {
                field: 'userName',
                title: '车主姓名'
            },{
                field: 'baseCarNo',
                title: '车牌号'
            }, {
                field: 'baseTerminalId',
                title: '设备编号'
            }, {
                field: 'baseTerminalSim',
                title: 'SIM卡号'
            } ,
                {
                    field:"baseTerminalStatus",
                    title:"设备状态",
                    formatter:function (value,row,index) {
                        var txt = "";
                        switch (parseInt(value)){
                            case 1:
                                txt = "启用";
                                break;
                            case 2:
                                txt = "停用";
                                break;
                            case 3:
                                txt = "拆机";
                                break;
                            default:
                                txt = "";
                        }
                        return txt
                    }
                },
                {
                    field: 'id',
                    title: '操作',
                    formatter:function (value,row,index) {
                        var opHtml = "";
                        var isEdit = AuthUtils.getOpAuthById("13_29");
                        var isDel = AuthUtils.getOpAuthById("13_30");
                        var isQianYi = AuthUtils.getOpAuthById("13_45");
                        if(isEdit){
                            opHtml+= "<button type=\"button\" class=\"btn  btn-theme\" style=\"margin-bottom: 3px;margin-top: 3px;margin-right: 3px;padding: 3px 6px;\" onclick='editDeviceView("+row.id+","+row.tId+")'>修 改</button>";
                        }
                        if(isDel){
                            opHtml+= "<button type=\"button\" class=\"btn btn-danger\"  style=\"margin-bottom: 3px;margin-top: 3px;padding: 3px 6px;margin-right: 3px;\" onclick='deleteRow("+row.id+")'>删 除</button>";
                        }
                        if(isQianYi){
                            opHtml+="<button type=\"button\" class=\"btn  btn-theme\" style=\"margin-bottom: 3px;margin-top: 3px;padding: 3px 6px;\" onclick='moveDeviceView("+row.id+","+row.tId+")'>迁 移</button>";
                        }
                        return opHtml
                    }
                }
            ]
        });
        dataTable.init();
    }


    
    /**
     * 初始化用户管理列表页面事件
     */
    function initEvent() {
        $("#btn_add").on("click",function () {
            $.link(viewAddPage_url);
        });
        $("#btn_addFast").on("click",function () {
            $.link(viewAddFastPage_url);
        });
        $("#btn_addMove").on("click",function () {
            selectionArr = dataTable.getAllSelections();
            if(selectionArr.length){
                $("#myModalMove").modal("show");
            }else{
                $.messageExt.alert("系统提示","请先选择设备！","warning");
            }
        });
        $("#sureMove").click(function () {
            //选择tree
            var selectedNode = tree_Obj.getCheckedNodes(true)[0];
            var selectName="无";
            if (selectedNode.isParent) {
                swal("选择错误", "此区域无法添加设备!", "warning");
                return false;
            } else {
                selectName=selectedNode.name;
            }
            var ids = [];
            for(var j=0;j<selectionArr.length;j++){
                ids.push(selectionArr[j].id)
            }
            $.ajax({
                type: "POST",
                url: "/editDeviceInfo/updateDept",
                cache: false,
                async: true,
                dataType: "json",
                data:{
                    carIds:ids.toString(),
                    deptId:selectedNode.id
                },
                success: function (data) {
                    $.messageExt.alert("系统提示","批量迁移成功！","success");
                    dataTable.refresh();
                }
            });
        });
        $(".selectUser").on("click",function () {
            $("#myTreeDialog").modal("show");
        });
        $("#reset").click(function () {
            $("#deptid").val("");
            $("#basecarno").val("");
            $("#deptname").val("");
            $("#baseterminalid").val("");
            $("#baseTerminalSim").val("");
        });
        $("#dosearch").click(function () {
            dataTable.refresh({query: {
                baseterminalid:$("#baseterminalid").val(),
                baseTerminalSim:$("#baseTerminalSim").val(),
                deptid:$("#deptid").val(),
                basecarno:$("#basecarno").val(),
            }})
        })
    }

    /**
     * 初始化用户管理编辑页面事件
     */
    function initEditDeviceInfoEvent() {
        $("#submitForm").on("click",function () {

            if($("#deptname").val() == ""){
                $.messageExt.alert("系统提示","所属用户为必填项！","error");
                return false
            }
            if($("#baseTerminalId").val() == ""){
                $.messageExt.alert("系统提示","设备编号为必填项！","error");
                return false
            }
            if($("#baseCarNo").val() == ""){
                $.messageExt.alert("系统提示","车牌号码为必填项！","error");
                return false
            }
            if($("#userName").val() == ""){
                $.messageExt.alert("系统提示","车主姓名为必填项！","error");
                return false
            }
            if($("#baseTerminalSim").val() == ""){
                $.messageExt.alert("系统提示","SIM卡号为必填项！","error");
                return false
            }
            if($("#baseTerminalProtocol").val() == ""){
                $.messageExt.alert("系统提示","设备协议为必填项！","error");
                return false
            }
            if($("#baseProtocolType").val() == ""){
                $.messageExt.alert("系统提示","设备型号为必填项！","error");
                return false
            }
            $.ajax({
                url:viewAddDevice_url,
                type:"POST",
                data:{
                    id:$("#baseId").val(),
                    deptId:$("#deptId").val(),
                    baseTerminalId:$("#baseTerminalId").val(),
                    baseTerminalSim:$("#baseTerminalSim").val(),
                    baseTerminalServicePw:$("#baseTerminalServicePw").val(),
                    baseTerminalProtocol:$("#baseTerminalProtocol").val(),
                    baseProtocolType:$("#baseProtocolType").val(),
                    baseTerminalPw:$("#baseTerminalPw").val(),
                    baseTerminalExeType:$("#baseTerminalExeType").val(),
                    baseTerminalStatus:$("#baseTerminalStatus").val(),
                    baseTerminalExeTime:$("#baseTerminalExeTime").val(),
                    baseCarNo:$("#baseCarNo").val(),
                    userName:$("#userName").val(),
                    appPass:$("#appPass").val()
                    //rate:$("#rate").val()
                },
                dataType:"json"
            }).done(function (result) {
                if(result.isSuccess === true){
                    $.messageExt.alert("系统提示","设备添加成功！","success");
                    $("#baseTerminalIdTwo").val($("#baseTerminalId").val());
                    // $("#baseTerminalIdTree").val($("#baseTerminalId").val());
                    $("#baseTerminalIdTwoHidden").val(result.data.terminal.id);
                    $("#baseTerminalIdTree").val(result.data.terminal.id);
                    $("#carMessage").find("#id").val(result.data.car.id);
                    $("#baseMessageForm").find("#baseId").val(result.data.terminal.id);
                    // $("#baseTerminalId").val("");
                    // $("#baseTerminalSim").val("");
                    // $("#deptId").val("");
                    //  $("#baseTerminalServicePw").val("");
                    //  $("#baseTerminalProtocol").val("");
                    //    $("#baseProtocolType").val("");
                    // $("#baseTerminalPw").val("");
                    //   $("#baseTerminalExeType").val("");
                    // $("#baseTerminalStatus").val("");
                    // $("#baseTerminalExeTime").val("");
                    //  $("#rate").val("")
                }else{
                    $.messageExt.alert("系统提示",result.message?result.message:"保存失败！","error");
                }
            })
        });
        $("#submitCarForm").on("click",function () {
            save();
        });
        $("#submitInstallForm").on("click",function () {
            if($("#baseTerminalSetupP").val() == ""){
                $.messageExt.alert("系统提示","安装人为必填项！","error");
                return false
            }
            if($("#baseTerminalSetupTime").val() == ""){
                $.messageExt.alert("系统提示","安装时间为必填项！","error");
                return false
            }
            if($("#baseTerminalSetupPart").val() == ""){
                $.messageExt.alert("系统提示","安装位置为必填项！","error");
                return false
            }
            // if($("#baseTerminalProtocol").val() == ""){
            //     $.messageExt.alert("系统提示","设备协议为必填项！","error");
            //     return false
            // }
            // if($("#baseProtocolType").val() == ""){
            //     $.messageExt.alert("系统提示","设备型号为必填项！","error");
            //     return false
            // }
            $.ajax({
                url:viewAddInstall_url,
                type:"POST",
                data:{
                    //deptId:$("#deptId").val(),
                    id:$("#baseTerminalIdTree").val(),
                    baseTerminalSetupPerson:$("#baseTerminalSetupP").val(),
                    baseTerminalSetupTime:$("#baseTerminalSetupTime").val(),
                    baseTerminalSetupPart:$("#baseTerminalSetupPart").val(),
                    baseTerminalSetupBusy:$("#baseTerminalSetupBusy").val(),
                    baseTerminalSetupAddr:$("#baseTerminalSetupAddr").val(),
                    baseTerminalSetupLimited:$("#baseTerminalSetupLimited").val(),
                },
                dataType:"json"
            }).done(function (result) {
                if(result.isSuccess === true){
                    $.messageExt.alert("系统提示","安装信息保存成功！","success");
                    // $("#baseTerminalIdTwo").val($("#baseTerminalId").val());
                    // $("#baseTerminalId").val("");
                    // $("#baseTerminalSetupP").val("");
                    // $("#deptId").val("");
                    // $("#baseTerminalSetupTime").val("");
                    // $("#baseTerminalSetupPart").val("");
                    // $("#baseTerminalSetupBusy").val("");
                    // $("#baseTerminalSetupAddr").val("");
                    // $("#baseTerminalSetupLimited").val("");
                }else{
                    $.messageExt.alert("系统提示",result.message?result.message:"保存失败！","error");
                }
            })
        });
        $("#back-view").click(function () {
            $.link(viewAccountList_url);
        });
        $("#baseMessageForm").validForm([
            {
                name:"baseTerminalSim",
                validate:{
                    type:"require",
                    message:"SIM卡号为必填项"
                }
            },
            {
                name:"baseTerminalProtocol",
                validate:[
                    {
                        type:"require",
                        message:"设备协议为必填项"
                    }
                ]
            },
            {
                name:"baseProtocolType",
                validate:[
                    {
                        type:"require",
                        message:"设备型号为必填项"
                    }
                ]
            },
            {
                name:"baseTerminalId",
                validate:[
                    {
                        type:"require",
                        message:"设备编号为必填项"
                    }
                ]
            },
            {
                name:"baseCarNo",
                validate:[
                    {
                        type:"require",
                        message:"车牌号码为必填项"
                    }
                ]
            },
            {
                name:"userName",
                validate:[
                    {
                        type:"require",
                        message:"车主姓名为必填项"
                    }
                ]
            }
        ]);
        $("#carMessageForm").validForm([
            // {
            //     name:"baseCarNo",
            //     validate:{
            //         type:"require",
            //         message:"车牌号为必填项"
            //     }
            // },
            {
                name:"baseCarDisMake",
                validate:[
                    {
                        type:"maxLength",
                        value:"4",
                        message:"设备协议为必填项"
                    }
                ]
            }
        ]);

        function save() {
            // var selectedNode = tree_Obj.getSelectedNodes()[0];
            // $("#deptTwoId").val();
            $('#carMessageForm').ajaxSubmit({
                type: 'post', // 提交方式 get/post
                dataType: 'json',
                url: '/baseCar/save', // 需要提交的 url
                beforeSubmit: function (formData, jqForm, options) {
                    // if (!$("#editForm").valid()) {
                    //     return false;
                    // }
                    if($("#baseTerminalIdTwo").val() == ""){
                        $.messageExt.alert("系统提示","请先保存基本信息","warning");
                        return false
                    }
                    if($("#baseCarNo").val() == ""){
                        $.messageExt.alert("系统提示","车牌号为必填项！","warning");
                        return false
                    }
                    if($("#baseCarBrand").val() == ""){
                        $.messageExt.alert("系统提示","车辆品牌为必填项！","warning");
                        return false
                    }
                    if($("#baseBarColor").val() == ""){
                        $.messageExt.alert("系统提示","车辆颜色为必填项！","warning");
                        return false
                    }
                    if($("#baseCarDisMake").val() && $("#baseCarDisMake").val().length > 4){
                        $.messageExt.alert("系统提示","里程补偿系数最大长度不能超过4位","warning");
                        return false
                    }


                },
                success: function (data) {
                    // data 保存提交后返回的数据，一般为 json 数据
                    // 此处可对 data 作相关处理
                    if (data.success) {
                        swal({
                            title: "系统提示",
                            text: data.msg,
                            type: "success"
                        });
                        // $("#myModal").setDefForm(validator);
                        //$('#carMessageForm').clearForm(true);
                        // $("#myModal").modal("hide");
                        //query(1);
                    } else {
                        swal({
                            title: "系统提示",
                            text: data.msg,
                            type: "error"
                        });
                    }
                },

            });
        }
    }
    function initTab() {
        $("#deviceTab").jqTab({
            tabs:[
                {
                    title:"基本信息",
                    selected:true,
                    elemId:"baseMessage"
                },
                {
                    title:"车辆信息",
                    selected:false,
                    elemId:"carMessage"
                },
                {
                    title:"安装信息",
                    selected:false,
                    elemId:"installMessage"
                }
            ]
        })
    }
    return{
        initDevicePage:function () {
            initTable();
            initEvent();
        },
        initEditDevicePage:function () {
            initEvent();
            initEditDeviceInfoEvent();
            initTab();
            var start = {
                elem: '#baseTerminalExeTime',
                format: 'YYYY-MM-DD hh:mm:ss',
//            min: laydate.now(), //设定最小日期为当前日期
                max: '2999-06-16 23:59:59', //最大日期
//            start: laydate.now(),
//            start: laydate.now() + ' 00:00:00',
                istime: true,
                istoday: false,
                festival: true, //是否显示节日
                choose: function (datas) {
                    if(datas){
                        end.min =datas.substring(0,10)+" 00:00:00"
                        end.start = datas.substring(0,10)+" 00:00:00"
                    }
//                end.min = datas; //开始日选好后，重置结束日的最小日期
//                end.start = datas //将结束日的初始值设定为开始日
                }
//            min: laydate.now(-1), //-1代表昨天，-2代表前天，以此类推
//            max: laydate.now(+1) //+1代表明天，+2代表后天，以此类推
            };
            var end = {
                elem: '#end',
                format: 'YYYY-MM-DD hh:mm:ss',
//            min: laydate.now(),
                max: '2999-06-16 23:59:59',
//            start: laydate.now() + ' 23:59:59',
                istime: true,
                istoday: false,
                festival: true, //是否显示节日
                choose: function (datas) {
                    var st=$("#start").val();
                    if(st>datas){
                        swal({
                            title: "系统提示",
                            text: "开始时间必须小于结束时间!",
                            type: "error"
                        });
//                    $("#end").val(laydate.now() + ' 23:59:59');
                    }else{
                        start.max = datas.substring(0,10)+" 23:59:59"; //结束日选好后，重置开始日的最大日期
                    }
                }
            };
            laydate(start);
            // laydate(end);
            $("#baseTerminalExeTime").val(laydate.now() + ' 00:00:00');
            // $("#end").val(laydate.now() + ' 23:59:59');


            var baseCarFactorystart = {
                elem: '#baseCarFactory',
                format: 'YYYY-MM-DD hh:mm:ss',
                max: '2999-06-16 23:59:59', //最大日期

                istime: true,
                istoday: false,
                festival: true, //是否显示节日
                choose: function (datas) {
                    end.min = datas; //开始日选好后，重置结束日的最小日期
                    end.start = datas //将结束日的初始值设定为开始日
                }

            };
            var baseCarBuyend = {
                elem: '#baseCarBuy',
                format: 'YYYY-MM-DD hh:mm:ss',
                max: '2999-06-16 23:59:59',
                istime: true,
                istoday: false,
                festival: true, //是否显示节日
                choose: function (datas) {
                    start.max = datas; //结束日选好后，重置开始日的最大日期
                }
            };
            laydate(baseCarFactorystart);
            laydate(baseCarBuyend);
            $("#baseCarFactory").val(laydate.now() + ' 00:00:00');
            $("#baseCarBuy").val(laydate.now() + ' 23:59:59');

            var baseTerminalSetupTimestart = {
                elem: '#baseTerminalSetupTime',
                format: 'YYYY-MM-DD hh:mm:ss',
                max: '2999-06-16 23:59:59', //最大日期

                istime: true,
                istoday: false,
                festival: true, //是否显示节日
                choose: function (datas) {
                    end.min = datas; //开始日选好后，重置结束日的最小日期
                    end.start = datas //将结束日的初始值设定为开始日
                }

            };
            laydate(baseTerminalSetupTimestart);
            $("#baseTerminalSetupTime").val(laydate.now() + ' 00:00:00');

        }
    }
}(jQuery);
    
function editDeviceView(id,tid) {
    $.link(viewAddPage_url + "?id="+id+"&tid="+tid);
}
function moveDeviceView(id,tid) {
    $("#myModalMove").modal("show");
    selectionArr = [];
    selectionArr.push({id:id});
    //$.link(viewAddPage_url + "?id="+id+"&tid="+tid);
}